import axios from "axios";

// 创建一个 axios 实例
const service = axios.create({
  baseURL: "", // 所有的请求地址前缀部分
  timeout: 600000, // 请求超时时间毫秒
  withCredentials: true, // 异步请求携带cookie
  transformResponse: [
    function (config) {
      // 对 data 进行任意转换处理

      return config;
    },
  ],
});

// 添加请求拦截器
service.interceptors.request.use(
  (config) => {
    return config;
  },

  (err) => {
    return Promise.reject(err);
  }
);

// 添加响应拦截器
service.interceptors.response.use(
  (res) => {
    const contentType = res.headers["content-type"];
 
    if (contentType && contentType.includes("octet - stream")) {
      return res;
    } else if (
      contentType &&
      contentType.includes(
        "vnd.openxmlformats-officedocument.spreadsheetml.sheet"
      )
    ) {
      return res;
    } else if (res.config.url == "/api/NozzleTable/CreateCheckNozzleTable") {
      return res;
    } else if (res.config.url == "/api/project/DownloadProjectFile") {
      return res;
    } else if (res.config.url == "/api/Department/DownloadDepartmentFile") {
      return res;
    } else if (res.config.url == "/api/equipment/ImportEquipInfosV2") {
      return res;
    } else {
      let data = res;
      if (res.data && res.data !== "True") {
        try {
          data = JSON.parse(res.data); 
        } catch (error) {
          return data;
        }
       
      }else{
        data = res.data;
      }
      if (data.code === 200) {
        return data;
      } else if (data.code === 405) {
        ElMessage({
          type: "error",
          message: "权限过期，请重新登录",
        });
        return;
      } else {
        return data;
      }
    }
  },
  (err) => {
    return Promise.reject(err);
  }
);

export default service;
